package com.ddm.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public boolean set(String key, Object value, long timeout) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            return true;
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis连接失败，跳过缓存操作: " + e.getMessage());
            return false;
        } catch (Exception e) {
            log.error("Redis操作失败: " + e.getMessage());
            return false;
        }
    }

    public Object get(String key) {
        try {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis连接失败，无法获取缓存: " + e.getMessage());
            return null;
        } catch (Exception e) {
            log.error("Redis获取操作失败: " + e.getMessage());
            return null;
        }
    }

    public boolean del(String key) {
        try {
            return key != null && Boolean.TRUE.equals(redisTemplate.delete(key));
        } catch (RedisConnectionFailureException e) {
            log.warn("Redis连接失败，无法删除缓存: " + e.getMessage());
            return false;
        } catch (Exception e) {
            log.error("Redis删除操作失败: " + e.getMessage());
            return false;
        }
    }
}
